﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Xml.Linq;
using ChoJu.ModelManager.Config;
using ChoJu.Single.DAL;
using ChoJuRating.View;
using ChongJu.Camera;
using ChongJu.EventManager;
using ChongJu.EventManager.ExchangePage;
using ChongJu.GlobalInfo;
using ChongJu.ModelManager.Camera;
using Microsoft.Practices.Prism.Commands;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Public.MvvmBase;
using Public.Tools;

namespace ChoJu.Single.ViewModel
{
    public class CameraVM : PropertyChangedBase
    {
        private Timer _timer;
        private int _type = 0;
        private string _dirRoot;
        public CameraVM()
        {
            SaveConfigCommand = new DelegateCommand(SaveConfigFunction);
            TakePictureCommand = new DelegateCommand(TakePictureFunction);
            VoiceCommand = new DelegateCommand(VoiceFunction);
            TakePictureOneCommand = new DelegateCommand(TakePictureOneFunction);
            UploadConfigCommand = new DelegateCommand(UploadCfgFunction);
            DownConfigCommand = new DelegateCommand(DownConfigFunction);
            TackCommand = new DelegateCommand<string>(TackFunction);

            //当页面切换时需要检测是否到相机参数页面，如果到了需要刷新页面config数据
            ExchangePageEvent.ExchangePageEventReportNew += ExchangePageEvent_ExchangePageEventReportNew;
            //Camera.Instance.ImageCallBackEvent += Instance_ImageCallBackEvent;
            Config = CameraConfig.CameraCfg;

            _timer = new Timer(1000 * 3);
            _timer.Elapsed += _timer_Elapsed;
            BtnSaveTxt = "保存图片";
            _dirRoot = Path.Combine(AppContext.BaseDirectory, "Config");
        }



        private void ExchangePageEvent_ExchangePageEventReportNew(PageEnum page)
        {
            //当页面切换时需要检测是否到相机参数页面，如果到了需要刷新页面config数据
            if (page == PageEnum.Camera)
            {
                Config = CameraConfig.CameraCfg;
            }

            AdminEnable = GlobalVar.IsAdmin;
        }

        #region Property


        public bool AdminEnable
        {
            get { return _adminEnable; }
            set { _adminEnable = value; OnPropertyChanged(() => AdminEnable); }
        }
        private bool _adminEnable = false;


        public CameraModel Config
        {
            get { return _config; }
            set { _config = value; OnPropertyChanged(() => Config); }
        }
        private CameraModel _config;


        public string BtnSaveTxt
        {
            get { return _btnSaveTxt; }
            set { _btnSaveTxt = value; OnPropertyChanged(() => BtnSaveTxt); }
        }
        private string _btnSaveTxt;


        #endregion


        #region Command

        public DelegateCommand SaveConfigCommand { get; }

        public DelegateCommand TakePictureCommand { get; }

        public DelegateCommand VoiceCommand { get; }

        public DelegateCommand TakePictureOneCommand { get; }


        public DelegateCommand UploadConfigCommand { get; }

        public DelegateCommand DownConfigCommand { get; }

        public DelegateCommand<string> TackCommand { get; }

        #endregion


        #region Function

        private void TakePictureOneFunction()
        {
            Camera.Instance.TakePicture();
            //if (BtnSaveTxt == "保存图片")
            //{
            //    _type = 1;
            //    GlobalVar.CurrentRunType = ChongJu.ModelManager.RunTypeEnum.Collection;
            //    BtnSaveTxt = "取消保存";
            //}
            //else
            //{
            //    _type = 0;
            //    GlobalVar.CurrentRunType = ChongJu.ModelManager.RunTypeEnum.Rating;
            //    BtnSaveTxt = "保存图片";
            //}
        }

        public void SaveConfigFunction()
        {
            try
            {
                Config.Width = CameraConfig.GetMultipleValue(Config.Width, 8);
                Config.Height = CameraConfig.GetMultipleValue(Config.Height, 4);
                OnPropertyChanged(() => Config);

                Camera.Instance.Stop();
                Camera.Instance.SetParams(Config, true);
                Camera.Instance.Start();
            }
            catch (Exception ex)
            {
                CJMsgBox.ShowDialog("写入参数到相机失败！");
            }

            var bol = CameraConfig.UpdateCameraCfg(Config);
            if (bol == false)
            {
                CJMsgBox.ShowDialog("保存参数错误");
                return;
            }

            CJMsgBox.ShowDialog("设置相机并保存参数完成");
        }

        private void TakePictureFunction()
        {
            _type = 0;
            if (_timer.Enabled == true)
            {
                //CommonEvent.OnRunLogger("tm: stop: " + _timer.Enabled);
                _timer.Stop();
            }
            else
            {
                //CommonEvent.OnRunLogger("tm: start:" + _timer.Enabled);
                _timer.Start();
            }
        }

        private void VoiceFunction()
        {
            new WindowVoice().Send("语音测试");
        }

        private void UploadCfgFunction()
        {
            if (Directory.Exists(_dirRoot) == false)
            {
                CJMsgBox.ShowDialog("没有配置文件");
                return;
            }

            var files = Directory.GetFiles(_dirRoot);
            if (files.Length == 0)
            {
                CJMsgBox.ShowDialog("没有配置文件项目");
                return;
            }

            List<ConfigSaveModel> lst = new List<ConfigSaveModel>();
            foreach (var file in files)
                lst.Add(new ConfigSaveModel()
                {
                    DeviceID = GlobalVar.DeviceID,
                    Name = new FileInfo(file).Name,
                    Content = File.ReadAllText(file)
                });

            var url = $"{Tool.GetConfig("api")}/config/upload";
            string json = JsonConvert.SerializeObject(lst);
            var data = Encoding.UTF8.GetBytes(json);

            var response = HttpReqest.PostBytes(url, data);
            JObject jsonObj = JObject.Parse(response);
            string code = (string)jsonObj["code"];
            if (code != "0")
                CJMsgBox.ShowDialog("上传失败");
            else
                CJMsgBox.ShowDialog("上传成功");
        }


        private void DownConfigFunction()
        {
            var url = $"{Tool.GetConfig("api")}/config/download?deviceID={GlobalVar.DeviceID}";
            var res = HttpReqest.Get(url);

            JObject jsonObj = JObject.Parse(res);
            string code = (string)jsonObj["code"];
            if (code != "0")
            {
                CJMsgBox.ShowDialog("没有配置文件");
                return;
            }

            var data = (JArray)jsonObj["data"];
            ConfigSaveModel[] arr = data.ToObject<ConfigSaveModel[]>();
            if (arr.Length == 0)
            {
                CJMsgBox.ShowDialog("服务端没有配置文件信息");
                return;
            }

            if (Directory.Exists(_dirRoot) == false)
                Directory.CreateDirectory(_dirRoot);

            foreach (var item in arr)
            {
                var path = Path.Combine(_dirRoot, item.Name);
                File.WriteAllText(path, item.Content);
            }
            CJMsgBox.ShowDialog("下载成功");
        }

        private void TackFunction(string id)
        {
            var idx = int.Parse(id);
            if (idx == 0)
            {
                Camera.Instance.TakeOne();
            }
            else if (idx == 1)
            {
                Camera.Instance.Stop();
                Camera.Instance.OpneLine1CloseLine2();
                Camera.Instance.Start();
                Camera.Instance.SetTriggerBySoftware();
            }
            else
            {
                Camera.Instance.Stop();
                Camera.Instance.OpneLine2CloseLine1();
                Camera.Instance.Start();
                Camera.Instance.SetTriggerByLine0();
            }
        }
        #endregion


        #region Event

        private void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            //CommonEvent.OnRunLogger("take pic");
            Camera.Instance.TakePicture();
        }

        private void Instance_ImageCallBackEvent(System.Drawing.Bitmap image, DateTime arg2)
        {
            if (_type != 1)
                return;

            var path = Path.Combine(AppContext.BaseDirectory, "Image_temp");
            if (Directory.Exists(path) == false)
                Directory.CreateDirectory(path);

            var file = Path.Combine(path, DateTime.Now.ToString("yyyyMMddhhssmm") + ".png");
            image.Save(file);

            //CommonEvent.OnRunLogger("保存图片成功");
        }

        #endregion


        #region Pritate Function


        #endregion
    }
}
